package config

import (
	"encoding/json"
	"errors"
	"fmt"
	"os"
	"path/filepath"

	"torler.com/qingyue/pkg/env"
)

type Rule struct {
	TocRules []TocRule `json:"toc_rules"`
}
type TocRule struct {
	Id     int    `json:"id"`
	Name   string `json:"name"`
	Rule   string `json:"rule"`
	Enable bool   `json:"enable"`
}

func LoadRule() (*Rule, error) {
	rule := &Rule{
		TocRules: []TocRule{},
	}
	err := loadFromJson("rule_toc", &rule.TocRules)
	if err != nil {
		return nil, errors.Join(err, errors.New("加载toc_rule错误"))
	}
	return rule, err
}

func loadFromJson(fileName string, dest any) error {
	name := fmt.Sprintf("%s.json", fileName)
	configPath := filepath.Join(env.GetConfigDir(), name)

	// 使用标准库直接读取和解析JSON数组
	data, err := os.ReadFile(configPath)
	if err != nil {
		return fmt.Errorf("failed to read config file: %w", err)
	}

	if err := json.Unmarshal(data, dest); err != nil {
		return fmt.Errorf("failed to unmarshal config: %w", err)
	}

	return nil
}
